package com.cqhz.quwan.ui.main.match

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.support.design.widget.TabLayout
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.support.v4.view.ViewPager
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import quickcore.webview.WebViewListener
import android.widget.TextView
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.StringUtils
import com.blankj.utilcode.util.TimeUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.cqhz.quwan.ActivityInject
import com.cqhz.quwan.R
import com.cqhz.quwan.model.AnalysisEventData
import com.cqhz.quwan.mvp.match.AnalysisEventContract
import com.cqhz.quwan.mvp.match.AnalysisEventPresenter
import com.cqhz.quwan.service.API
import com.cqhz.quwan.service.API.Companion.matchLiveDetail
import com.cqhz.quwan.ui.base.GoBackActivity
import com.cqhz.quwan.ui.main.match.common.Key
import com.cqhz.quwan.ui.main.match.common.Utils
import com.cqhz.quwan.ui.main.match.fragment.*
import com.cqhz.quwan.util.CLogger
import com.cqhz.quwan.util.JSBridgeInterface
import com.cqhz.quwan.util.PreferenceHelper
import com.tencent.smtt.sdk.ValueCallback
import com.tencent.smtt.sdk.WebSettings
import com.tencent.smtt.sdk.WebView
import kotlinx.android.synthetic.main.activity_match_analysis.*
import me.militch.quickcore.core.HasDaggerInject
import quickcore.webview.WebViewSetup
import java.text.MessageFormat
import java.text.SimpleDateFormat
import java.util.*
import javax.inject.Inject

/**
 * 赛事分析
 *
 * @author whamu2
 * @date 2018/7/16
 */
class MatchAnalysisActivity : GoBackActivity(), View.OnClickListener, AnalysisEventContract.View, HasDaggerInject<ActivityInject>, WebViewListener {

    @Inject
    lateinit var analysisEventPresenter: AnalysisEventPresenter
    private var matchId: String? = null
    private var leagueId: String? = null
    internal var situationFragment: MatchSituationFragment? = null

    override fun setTitleView(title: String?) {

    }

    override fun pageStart(view: WebView?, url: String?, favicon: Bitmap?) {

    }

    override fun pageEnd(view: WebView?, url: String?) {

    }

    override fun loadUrl(webView: WebView?, isWebScheme: Boolean, scheme: String?, url: String?): Boolean {
        val log = CLogger(this::class.java)
        log.e("url", url ?: "")
        if (!isWebScheme) {
        } else {
            if (url!!.contains("http://m.leisu.com/app/download")) {
                showToast("暂无视频直播")
            } else {
                this.wv_video.loadUrl(url)
            }
        }
        return true
    }

    override fun onDownload(url: String?) {

    }

    override fun onOpenFile(`is`: Boolean, callback: ValueCallback<Array<Uri>>?, callback2: ValueCallback<Uri>?) {

    }

    private val mOnPageChangeListener = object : ViewPager.SimpleOnPageChangeListener() {
        override fun onPageSelected(position: Int) {
            super.onPageSelected(position)
            if (position == 0) {
                vp_content.currentItem = 0
            }
        }
    }

    override fun titleBarText(): String? {
        return "赛事分析"
    }

    override fun inject(inject: ActivityInject) {
        inject.inject(this)
    }

    override fun layout(): Int {
        return R.layout.activity_match_analysis
    }

    override fun initView() {
        analysisEventPresenter.attachView(this)
        matchId = intent.getStringExtra(KEY_ANALYSIS)
        leagueId = intent.getStringExtra(KEY_LEAGUE)
        setupTitleBar()
        analysisEventPresenter.getAnalysisEvent(matchId)
        setupFooter()
        LogUtils.e(TAG, "matchId = $matchId; leagueId = $leagueId")

        val dir = getDir("database", Context.MODE_PRIVATE).path
        val jsBridge = JSBridgeInterface()
        WebViewSetup.builder()
                .setWebViewClient(this)
                .setLocationDbPath(dir)
                .setCacheMode(WebSettings.LOAD_NO_CACHE)
                .build().setupWebView(wv_video)
        wv_video.addJavascriptInterface(jsBridge, "Android")

        action_play.setOnClickListener {
            wv_video.visibility = View.VISIBLE
            action_close.visibility = View.VISIBLE
            rl_match_info.visibility = View.GONE
            val url = "${API.matchLiveDetail}?id=$leagueId"
            wv_video.loadUrl(url)
        }
        action_close.setOnClickListener {
            wv_video.visibility = View.GONE
            action_close.visibility = View.GONE
            rl_match_info.visibility = View.VISIBLE
        }
    }

    override fun context(): Context {
        return this
    }

    /**
     * 标题栏
     */
    private fun setupTitleBar() {
        val mTitleTextView = findViewById<TextView>(R.id.bar_text)
        val mBackImageView = findViewById<ImageView>(R.id.bar_left)
        mTitleTextView.text = getString(R.string.str_match_analysis)
        mBackImageView.setImageResource(R.drawable.icon_back)
        mBackImageView.setOnClickListener(this)
    }

    @SuppressLint("SetTextI18n")
    override fun matchEvent(event: AnalysisEventData?) {
        if (event != null) {
            tv_host.text = event.host_team
            tv_guest.text = event.guest_team
            PreferenceHelper.getInstance(this).putString("host_team", event.host_team)
            PreferenceHelper.getInstance(this).putString("guest_team", event.guest_team)
            val time = TimeUtils.millis2String(event.match_time, SimpleDateFormat("MM-dd HH:mm", Locale.getDefault()))
            tv_title.text = MessageFormat.format("{0} {1}", time, event.league)
            Glide.with(this)
                    .load(event.host_logo)
                    .apply(RequestOptions.errorOf(R.mipmap.ic_logo_default))
                    .apply(RequestOptions.circleCropTransform())
                    .into(icon_host)
            Glide.with(this)
                    .load(event.guest_logo)
                    .apply(RequestOptions.errorOf(R.mipmap.ic_logo_default))
                    .apply(RequestOptions.circleCropTransform())
                    .into(icon_guest)

            action_play.visibility = if (!StringUtils.isEmpty(leagueId)) View.VISIBLE else View.GONE
            when (event.status) {
                Key.MatchState.STATE_NO // 未开始
                -> {
                    tv_host_score.text = ""
                    tv_guest_score.text = ""
                    tv_single.text = "VS"
                    tv_state.text = "未开始"
                }
                Key.MatchState.STATE_START // 进行中
                -> {
                    tv_host_score.text = if (TextUtils.isEmpty(event.score)) "" else Utils.getSingleScore(event.score, 0)
                    tv_guest_score.text = if (TextUtils.isEmpty(event.score)) "" else Utils.getSingleScore(event.score, 1)
                    tv_single.text = "-"
                    tv_state.text = "进行中"
                }
                Key.MatchState.STATE_COMPLATE // 结束
                -> {
                    tv_host_score.text = if (TextUtils.isEmpty(event.score)) "" else Utils.getSingleScore(event.score, 0)
                    tv_guest_score.text = if (TextUtils.isEmpty(event.score)) "" else Utils.getSingleScore(event.score, 1)
                    tv_single.text = "-"
                    tv_state.text = "已结束"
                }
                Key.MatchState.STATE_PAUSE // 暂停
                -> {
                    tv_host_score.text = ""
                    tv_guest_score.text = ""
                    tv_single.text = "VS"
                    tv_state.text = "暂停"
                }
                Key.MatchState.STATE_DELAY // 推迟
                -> {
                    tv_host_score.text = ""
                    tv_guest_score.text = ""
                    tv_single.text = "VS"
                    tv_state.text = "推迟"
                }
                Key.MatchState.STATE_CANCEL // 取消
                -> {
                    tv_host_score.text = ""
                    tv_guest_score.text = ""
                    tv_single.text = "VS"
                    tv_state.text = "取消"
                }
                else -> {
                    tv_host_score.text = ""
                    tv_guest_score.text = ""
                    tv_single.text = "VS"
                    tv_state.text = "未开始"
                }
            }

        }
    }

    /**
     * 底部分栏
     */
    private fun setupFooter() {
        val mTabLayout = findViewById<TabLayout>(R.id.tablayout)
        val adapter = TabAdapter(supportFragmentManager)
        situationFragment = MatchSituationFragment.newInstance(matchId)
        adapter.addTab(situationFragment!!, getString(R.string.str_match_situation))
        adapter.addTab(IntegralFragment.newInstance(matchId, leagueId), getString(R.string.str_match_integral))
        adapter.addTab(AnalysisFragment.newInstance(matchId), getString(R.string.str_match_page_analysis))
        adapter.addTab(PredictionFragment.newInstance(matchId), getString(R.string.str_match_prediction))
        adapter.addTab(OddsFragment.newInstance(matchId), getString(R.string.str_match_odds))
        vp_content.offscreenPageLimit = 4
        vp_content.adapter = adapter
        mTabLayout.setupWithViewPager(vp_content, false)
        vp_content.currentItem = 2
        vp_content.addOnPageChangeListener(mOnPageChangeListener)
        mTabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                val position = tab.position
                if (position == 0 && situationFragment != null) {
                    situationFragment!!.setupLoad(matchId)
                }
            }

            override fun onTabUnselected(tab: TabLayout.Tab) {

            }

            override fun onTabReselected(tab: TabLayout.Tab) {

            }
        })
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.bar_left -> finish()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        analysisEventPresenter.detachView()
        PreferenceHelper.getInstance(this).putString("host_team", "")
        PreferenceHelper.getInstance(this).putString("guest_team", "")
    }

    private class TabAdapter internal constructor(fm: FragmentManager) : FragmentPagerAdapter(fm) {
        private val fragments = ArrayList<Fragment>()
        private val titles = ArrayList<String>()

        internal fun addTab(fragment: Fragment, title: String) {
            fragments.add(fragment)
            titles.add(title)
        }

        override fun getItem(position: Int): Fragment {
            return fragments[position]
        }

        override fun getCount(): Int {
            return fragments.size
        }

        override fun getPageTitle(position: Int): CharSequence? {
            return titles[position]
        }
    }

    companion object {
        private val TAG = MatchAnalysisActivity::class.java.simpleName
        private const val KEY_ANALYSIS = "Analysis"
        private const val KEY_LEAGUE = "league"

        fun start(context: Context?, matchId: String?, lid: String?) {
            if (!TextUtils.isEmpty(matchId)) {
                val starter = Intent(context, MatchAnalysisActivity::class.java)
                starter.putExtra(KEY_ANALYSIS, matchId)
                starter.putExtra(KEY_LEAGUE, lid)
                context?.startActivity(starter)
            }
        }
    }
}
